import ebus from './ebus.js'
// var nats = require('websocket-nats')
var nats = require('./websocket-nats/index.js')
import debugCfg from './debugCfg'

var hostname = window.location.hostname
var gPort = window.location.port
if (process.env.NODE_ENV != 'production') {
  hostname = debugCfg.serverIp
  gPort = debugCfg.serverPort
}

export function NatsApi() {
  // 推送
  this.Publish = function(uri, req, callback){
    var sid = this.conn.publish(uri, req,  function (msg) {
     callback(msg)
    }.bind(this)) 
  }

  //连接
  this.CreatConnect = function (optin) {

    return new Promise(function (resolve, reject) {
      var host = ''
      if(optin && optin.url){
        host = optin.url
      } else{
        host = hostname
      }
      this.conn = nats.connect({
        reconnect: false,
        // verbose: true,
        // url: 'ws://' + host + `:${gPort}/_ws/stbp`
        url: `ws://${host}:${gPort}/_ws/stbp`
      },function(res){
        resolve('connct')
        // ebus.emit('connct')
      },function(res){
        ebus.emit('disconnct')
        reject('timeout');
        // console.warn('request timeout...');
      })
      setTimeout(function () {        
        reject('timeout');
      }, 3000)
    }.bind(this));
    
  }
  //断开连接
  this.DisConnect = function () {
    try {
      if (this.conn) {
        this.conn.close()
        this.conn = null
      }
    } catch (err) {
      console.warn('Close Connection Error!', err);
    }      

    
  }
  //订阅
  this.onSubscribe = function (topic, callback) {
    var sid = this.conn.subscribe(topic, function (msg) {
      callback(msg)
      console.log('msg:', msg)
    }.bind(this))   
  }
  //取消订阅
  this.onUnsubscribe = function (sid) {
    this.conn.unsubscribe(sid)
  }
  //发送请求
  this.onRequest = function (subject, opt_msg, opt_options, clientId, callback) {
    console.log('send:', subject)
    console.log('option:', opt_msg)
    return new Promise(function (resolve, reject) {
      this.conn.request(subject, opt_msg, opt_options, clientId, function(msg, reply){ 
        console.log(subject + ':', msg);               
        resolve(msg)
        if(typeof(callback) == 'function'){
          callback(msg, reply)
        }        
      }.bind(this));
      setTimeout(function () {
        reject('timeout');
        // console.warn('request timeout: ', subject);
      }, 5000)
    }.bind(this));   
    
  }

  this.isConnected = function () {
    if (this && this.conn && this.conn.isConnected()) {      
      return true
    } else {
      console.log('DisConnected')
      return false
    }
  }
}


export var api = new NatsApi() //通用
export var getHostName = function () {
  return hostname;
}
